package com.jl.magic.images;

import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.*;

/**
 * @author jiangli
 */
public class ColorConverts {

    public static BufferedImage doGray(BufferedImage src) {
        ColorConvertOp filterObj = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
        return filterObj.filter(src, null);
    }

    public static BufferedImage doBlur(BufferedImage bi) {
        if (bi.getType() == BufferedImage.TYPE_3BYTE_BGR) {
            bi = convertType(bi, BufferedImage.TYPE_INT_RGB);
        }

        float ninth = 1.0f / 9.0f;
        float[] blurKernel = {
                ninth, ninth, ninth,
                ninth, ninth, ninth,
                ninth, ninth, ninth
        };
        BufferedImageOp blurFilter =
                new ConvolveOp(new Kernel(3, 3, blurKernel));
        return blurFilter.filter(bi, null);
    }

    public static BufferedImage doBinaryImage(BufferedImage bi) {
        //bi = doGray(bi);
        byte[] threshold = new byte[256];
        for (int i = 0; i < 256; i++) {
            threshold[i] = (i < 128) ? (byte) 0 : (byte) 255;
        }
        BufferedImageOp thresholdOp = new LookupOp(new ByteLookupTable(0, threshold), null);
        return thresholdOp.filter(bi, null);
    }

    public static BufferedImage doScale(BufferedImage bi, double sx, double sy) {
        AffineTransformOp atfFilter = new AffineTransformOp(
                AffineTransform.getScaleInstance(sx, sy),
                AffineTransformOp.TYPE_BILINEAR);
        int nw = (int) (bi.getWidth() * sx);
        int nh = (int) (bi.getHeight() * sy);
        BufferedImage result = new BufferedImage(
                nw, nh, BufferedImage.TYPE_3BYTE_BGR);
        return atfFilter.filter(bi, result);
    }

    /* 改变图像类型 */
    private static BufferedImage convertType(BufferedImage src, int type) {
        ColorConvertOp cco = new ColorConvertOp(null);
        BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), type);
        cco.filter(src, dest);
        return dest;
    }

}
